import Flutter
import UIKit
//import Photos
//import TZImagePickerController
import CropViewController
import HXPHPicker

public class SwiftMediaPickerPlugin: NSObject, FlutterPlugin {
    var isCompress:Bool = false
    var compressQuality:CGFloat = 0.8
    var isEnableCrop:Bool = false
    var isGif = false
    
    var pickerResult:FlutterResult?
    
    public static func register(with registrar: FlutterPluginRegistrar) {
        let channel = FlutterMethodChannel(name: "media_picker", binaryMessenger: registrar.messenger())
        let instance = SwiftMediaPickerPlugin()
        registrar.addMethodCallDelegate(instance, channel: channel)
    }
    
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        print("\(call.method)")
        switch call.method {
        case "chooseImg":
            getImage(call, result: result)
        case "chooseVideo":
            getVideo(call, result: result)
        case "chooseAudio":
            getAudio(call, result: result)
        default:
            break
        }
    }
    
    func getImage(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        guard let arg = call.arguments as? [String:Any] else { return }
        guard let maxNumber = arg["max"] as? Int,
              let isEnableCrop = arg["isCrop"] as? Bool,
              let isCamera = arg["isCamera"] as? Bool,
              let circleDimmedLayer = arg["isCircle"] as? Bool,
              let isCompress = arg["isCompress"] as? Bool,
              let compressQuality = arg["quality"] as? Int,
              let isGif = arg["isGif"] as? Bool
        else {
            return result(FlutterError(code: "-1", message: "错误参数", details: "参数都不可为空, 需要设置默认值"))
        }
        self.isEnableCrop = isEnableCrop
        self.isCompress = isCompress
        self.isGif = isGif
        self.compressQuality = CGFloat(compressQuality)/100.0;
        
        let config = PickerConfiguration.init()
        config.selectOptions = isGif ? .gifPhoto : .photo
        config.selectMode = maxNumber == 1 ? .single : .multiple
        config.allowSelectedTogether = false
        config.albumShowMode = .normal
//        config.photoSelectionTapAction = .quickSelect
        config.maximumSelectedCount = maxNumber
        config.isCacheCameraAlbum = false
        config.previewView.bottomView.originalButtonHidden = true
        config.photoList.bottomView.originalButtonHidden = true
        
        let vc = PhotoPickerController.init(config: config)
        vc.pickerDelegate = self
        vc.autoDismiss = false
        vc.modalPresentationStyle = .fullScreen
        vc.isOriginal = true
        pickerResult = result
        UIApplication.shared.keyWindow?.rootViewController?.present(vc, animated: true, completion: nil)
        return
    }

    func getVideo(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
//         guard let arg = call.arguments as? [String:Any] else { return }
//         guard let maxNumber = arg["max"] as? Int else {
//             return result(FlutterError(code: "-1", message: "错误参数", details: "参数都不可为空, 需要设置默认值"))
//         }
        let config = PickerConfiguration.init()
        config.selectOptions = .video
        config.selectMode = .single//maxNumber == 1 ? .single : .multiple
        config.allowSelectedTogether = false
        config.albumShowMode = .normal
//         config.maximumSelectedCount = maxNumber
        config.isCacheCameraAlbum = false
        config.previewView.bottomView.originalButtonHidden = true
        config.photoList.bottomView.originalButtonHidden = true

        let vc = PhotoPickerController.init(config: config)
        vc.pickerDelegate = self
        vc.autoDismiss = false
        vc.modalPresentationStyle = .fullScreen
        vc.isOriginal = true
        pickerResult = result
        UIApplication.shared.keyWindow?.rootViewController?.present(vc, animated: true, completion: nil)
    }

    func getAudio(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        let documentPicker = UIDocumentPickerViewController(documentTypes: ["public.audio"], in: .import)
        documentPicker.delegate = self
        documentPicker.allowsMultipleSelection = false
        documentPicker.modalPresentationStyle = .fullScreen
        self.pickerResult = result
        UIApplication.shared.keyWindow?.rootViewController?.present(documentPicker, animated: true, completion: nil)
    }
}

extension SwiftMediaPickerPlugin: PhotoPickerControllerDelegate, CropViewControllerDelegate {
    //
    public func pickerController(didCancel pickerController: PhotoPickerController) {
        if let pickerResult = self.pickerResult {
            pickerResult(nil)
        }
        self.pickerResult = nil
        pickerController.dismiss(animated: true, completion: nil)
    }
    
    public func pickerController(_ pickerController: PhotoPickerController, didFinishSelection result: PickerResult) {
        if (pickerController.config.selectOptions.isVideo) {
            //
            let locals = result.photoAssets.map { pa in
                return pa.phAsset?.localIdentifier
            }
            result.getVideoURL { [weak self] urls in
                var paths:[Any] = []
                for url in urls.enumerated() {
                    paths.append([
                            "path": url.element.path,
                            "localIdentifier": locals[url.offset],
                            "size": self?.getFileSize(atPath: url.element.path) ?? 0,
                        ])
                }
                self?.pickerResult?(paths)
                self?.pickerResult = nil
                pickerController.dismiss(animated: true, completion: nil)
            }
            return
        }
        // 可编辑图片的情况: 单张图片
        if (isEnableCrop && result.photoAssets.count == 1 && self.isGif == false) {
            result.getImage { images in
                // 剪切第一张
                let vc = CropViewController(image: images[0])
                vc.rotateButtonsHidden = true
                vc.hidesNavigationBar = true
                vc.aspectRatioPickerButtonHidden = true
                vc.aspectRatioPreset = .presetSquare
                vc.resetAspectRatioEnabled = false
                vc.aspectRatioLockEnabled = true
                vc.delegate = self
                // 按钮文字配置
                vc.cancelButtonTitle = "取消"
                vc.doneButtonTitle = "完成"
                pickerController.pushViewController(vc, animated: true)
            }
        } else {
            result.getURLs { [weak self] urls in
                let paths = urls.map { (url) -> [String:Any] in
                    return [
                        "path": url.path,
                        "size": self?.getFileSize(atPath: url.path) ?? 0,
                    ]
                }
                self?.pickerResult?(paths)
                self?.pickerResult = nil
                pickerController.dismiss(animated: true, completion: nil)
            }
        }
    }
    
    public func cropViewController(_ cropViewController: CropViewController, didFinishCancelled cancelled: Bool) {
        cropViewController.dismiss(animated: true)
    }
    
    public func cropViewController(_ cropViewController: CropViewController, didCropToImage image: UIImage, withRect cropRect: CGRect, angle: Int) {
        let path = writeImageToTemporaryDirectory(image)
        pickerResult?([["path": path, "size": getFileSize(atPath: path ?? "") ?? 0]])
        pickerResult = nil
        cropViewController.dismiss(animated: true)
    }
    
    func writeImageToTemporaryDirectory(_ image: UIImage) -> String? {
        // 获取应用程序的临时目录路径
        let tmpDirectory = NSTemporaryDirectory()

        // 在临时目录中创建一个唯一的文件名
        let fileName = "\(UUID().uuidString).png"
        let filePath = (tmpDirectory as NSString).appendingPathComponent(fileName)

        // 将UIImage对象转换为PNG数据
        guard let pngData = image.pngData() else {
            return nil
        }

        // 将PNG数据写入到临时目录的文件中
        do {
            try pngData.write(to: URL(fileURLWithPath: filePath), options: .atomic)
        } catch {
            print("Failed to write image data to temporary file: \(error)")
            return nil
        }

        return filePath
    }

    // 获取文件大小
    func getFileSize(atPath filePath: String) -> Int64? {
        let fileManager = FileManager.default

        // 检查文件是否存在
        if fileManager.fileExists(atPath: filePath) {
            do {
                let fileAttributes = try fileManager.attributesOfItem(atPath: filePath)
                if let fileSize = fileAttributes[FileAttributeKey.size] as? Int64 {
                    return fileSize
                }
            } catch {
                print("Failed to retrieve file attributes: \(error)")
            }
        } else {
            print("File does not exist at path: \(filePath)")
        }

        return nil
    }
}

extension SwiftMediaPickerPlugin: UIDocumentPickerDelegate {
    // 处理选择的音频文件
    public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        guard let selectedFileURL = urls.first else {
            self.pickerResult?(nil)
            self.pickerResult = nil
            return
        }
        self.pickerResult?([["path": selectedFileURL.path.replacingOccurrences(of: "file:///", with: "/")]])
        self.pickerResult = nil
    }

    // 取消选择文件
    public func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        controller.dismiss(animated: true, completion: nil)
        // 处理取消选择文件的情况
        self.pickerResult?(nil)
        self.pickerResult = nil
    }
}
